//
//  SWOrderListViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/19.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit

class SWOrderCellViewModel
{
    var order:SWOrder
    var progress:CGFloat = 0
    
    init(order:SWOrder)
    {
        self.order = order
    }
}

class SWOrderListViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,SWAPIComponent,NullDataStatusProtocol,ClickActionDelegate
{
    var nullDataView:UIView?
    
    private var _list:[SWOrderCellViewModel] = []
    
    lazy private var _tableView:UITableView = UITableView()
    
    deinit
    {
        SWNotificationCenter.removeObserver(self)
        trace("DEINIT SWOrderListViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        title = "我的订单"
        
        _tableView.frame = view.bounds
        //_tableView.contentInset = UIEdgeInsetsMake(15, 0, 0, 0)
        _tableView.backgroundColor = UIColor(hex:0xefefef)
        _tableView.separatorStyle = .none
        _tableView.tableFooterView = UIView()
        _tableView.rowHeight = SWThemeStyle.OrderCellHeight
        _tableView.dataSource = self
        _tableView.delegate = self
        view.addSubview(_tableView)
        
        setupRefreshControl()
        nullDataViewSetup()
        
        SWNotificationCenter.addObserver(self, selector: #selector(paySuccessNotification(_:)), name: NotificationName.PaySuccess, object: nil)
        
        SWNotificationCenter.addObserver(self, selector: #selector(uploadProgressChangedNotification(_:)), name: NotificationName.UploadProgressChanged, object: nil)
        
        beginRefreshing()
    }
    
    private func nullDataViewSetup()
    {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(nullDataViewTapped))
        setupNullDataView(withText: "加载失败，点击重试", container: view)
        nullDataView?.isUserInteractionEnabled = true
        nullDataView?.addGestureRecognizer(tapGesture)
    }
    
    private func setupRefreshControl()
    {
        let header:MJRefreshNormalHeader = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.reloadData()
        })
        header.lastUpdatedTimeLabel?.isHidden = true
        _tableView.mj_header = header
    }
    
    private func beginRefreshing()
    {
        _tableView.mj_header?.beginRefreshing()
    }
    
    private func endRefreshing()
    {
        _tableView.mj_header?.endRefreshing()
    }
    
    private func reloadData()
    {
        let req = SWOrderListFetchReq()
        req.successCallback = {[weak self] response,_ in
            if let response = response as? SWOrderListFetchRsp,
                let orders:[SWOrder] = response.orders?.flatMap({SWOrder(response: $0)})
            {
                self?._list = orders.map({SWOrderCellViewModel(order:$0)})
                self?._tableView.reloadData()
                self?.endRefreshing()
            }
            else
            {
                self?.loadFail()
            }
        }
        req.failCallback = {[weak self] error in
            self?.loadFail()
        }
        load(req)
    }
    
    private func loadFail()
    {
        endRefreshing()
        setNullDataViewHidden(false)
    }
    
    private func purchaseRequisitionFetch(_ orderID:String)
    {
        let req = SWPurchaseRequisitionFetchReq()
        req.orderID = orderID
        req.successCallback = {[weak self] response,_ in
            if let requisitionRsp = (response as? SWPurchaseRequisitionFetchRsp)?.requisition,
                let requisition = SWPurchaseRequisition(response: requisitionRsp)
            {
                SVProgressHUD.dismiss()
                let paymentViewController = SWPaymentViewController(requisition: requisition)
                self?.navigationController?.pushViewController(paymentViewController, animated: true)
            }
            else
            {
                SVProgressHUD.showError(withStatus: SWError.DefaultNetworkError.message)
            }
        }
        req.failCallback = {[weak self] error in
            SVProgressHUD.showError(withStatus: error.message)
        }
        SVProgressHUD.show(withStatus: "支付中...")
        load(req)
    }
    
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let index:Int = indexPath.row
        var cell:UITableViewCell?
        let identifier:String = "SWOrderCell"
        cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil
        {
            cell = SWOrderCell(style: .default, reuseIdentifier: identifier, cellWidth: view.width)
            (cell as? SWOrderCell)?.delegate = self
        }
        (cell as? SWOrderCell)?.order = _list.valueAt(index)?.order
        (cell as? SWOrderCell)?.progress = _list.valueAt(index)?.progress ?? 0
        return cell ?? UITableViewCell(style: .default, reuseIdentifier: "")
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: false)
        if let order = _list.valueAt(indexPath.row)?.order,
            let orderID = order.orderID,orderID != ""
        {
            let viewController = SWOrderDetailViewController(orderID: orderID)
            navigationController?.pushViewController(viewController, animated: true)
        }
    }
    
    func view(_ view:UIView, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Pay
        {
            if let cell = view as? UITableViewCell,
               let indexPath = _tableView.indexPath(for: cell),
               let order = _list.valueAt(indexPath.row)?.order,
               let orderID = order.orderID,orderID != ""
            {
                purchaseRequisitionFetch(orderID)
            }
        }
    }
    
    @objc private func nullDataViewTapped()
    {
        reloadData()
    }
    
    @objc private func paySuccessNotification(_ notification:Notification)
    {
        print("paySuccessNotification")
        if let orderID = notification.userInfo?[SWKey.orderID] as? String,
           let index = _list.index(where: {($0.order.orderID ?? "") == orderID})
        {
            _list.valueAt(index)?.order.status = SWOrderStatus.purchased
            _tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
        }
    }
    
    @objc private func uploadProgressChangedNotification(_ notification:Notification)
    {
        print("uploadProgressChangedNotification")
        if let orderID = notification.userInfo?[SWKey.orderID] as? String,
            let index = _list.index(where: {($0.order.orderID ?? "") == orderID}),
            let item = _list.valueAt(index)
        {
            let progress:CGFloat = notification.userInfo?[SWKey.progress] as? CGFloat ?? 0
            item.progress = progress
            _tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
        }
    }
    
    
}
